package kafka.utils;

import kafka.config.KafkaConfig;
import kafka.producer.BaseKafkaProducer;
import kafka.producer.KafkaProducerManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;


/**
 * @author huypva
 */
public class KafkaUtils {
    private KafkaUtils() {
    }

    private static final Log LOGGER = LogFactory.getLog(KafkaUtils.class);

    public static boolean sendMsg(KafkaConfig config, String msg) {
        try {
            BaseKafkaProducer producer = KafkaProducerManager.getClient(config);
            return producer.sendMessage(msg);
        } catch (Exception ex) {
            LOGGER.error("Send msg to kafka error!" + ex.getMessage(), ex);
            return false;
        }
    }

    public static boolean sendMsg(KafkaConfig config, String topic, String msg) {
        try {
            BaseKafkaProducer producer = KafkaProducerManager.getClient(config);
            return producer.sendMessage(topic, msg);
        } catch (Exception ex) {
            LOGGER.error("Send msg to kafka error!" + ex.getMessage(), ex);
            return false;
        }
    }

    public static Properties getProperties(String configPath) {
        Properties prop = new Properties();
        InputStream input = null;
        try {
            input = Files.newInputStream(Paths.get(configPath));
            prop.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return prop;
    }

}
